import Taro, { Component, Config, getCurrentPages } from '@tarojs/taro'
import { View, Text, Form } from '@tarojs/components'
import { AtButton, AtModal, AtSwipeAction, AtIcon, AtForm } from 'taro-ui';
import { observer, inject } from '@tarojs/mobx'
import Stores from '../../../stores/storeIdentifier'
import OrderStore from "../../../stores/orderStore";
import './index.scss'
import { UserShippingAddressDto } from '../../../services/cart/dto/userShippingAddressDto';
import { UserShippingAddressInputDto } from '../../../services/cart/dto/userShippingAddressInputDto';
import WxOpenStore from 'src/stores/wxOpenStore';

export interface IIndexProps {
  orderStore: OrderStore
  wxOpenStore: WxOpenStore
}

@inject(Stores.OrderStore, Stores.WxOpenStore)
@observer
class Index extends Component<IIndexProps> {

  state = {
    isOpened: false,
    id: 0
  };
  canDelete: boolean
  editSuccess: boolean
  address: UserShippingAddressInputDto = new UserShippingAddressInputDto();
  addressList: UserShippingAddressDto[] = [];
  swiperOptions: Array<any> = [
    {
      text: '删除',
      style: {
        backgroundColor: '#FF4949'
      }
    }
  ];

  constructor(props: any) {
    super(props);
    if (this.$router.params.prev != "order") {
      this.canDelete = false
    }
    else {
      this.canDelete = true
    }
  }

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '地址管理'
  }

  async componentWillMount() {
    await this.getAddressList();
  }

  componentWillReact() {
    console.log('componentWillReact')
  }

  componentWillUnmount() {
  }

  async componentDidShow() {
    var pages = getCurrentPages()
    let prev = pages[pages.length - 1]
    if (prev.data.editSuccess) {
      await this.getAddressList()
    }
  }

  async getAddressList() {
    await this.props.orderStore.getMyAddressList();

    const { addressList } = this.props.orderStore;
    this.addressList = addressList;
    this.setState({});
  }

  async gotoAddressEdit(e) {
    e.stopPropagation();

    if (!e.currentTarget.dataset.id) {
      await this.props.wxOpenStore.createFormIds([{ formId: e.detail.formId, formIdType: 0 }])
      Taro.navigateTo({ url: '/pages/profile/address/edit/index' });
    }
    else
      Taro.navigateTo({
        url: `/pages/profile/address/edit/index?id=${e.currentTarget.dataset.id}`,
      })
  }

  gotoAddressImport() {
    Taro.navigateTo({
      url: '/pages/profile/address/import/index'
    })
  }

  delete(e) {
    this.setState({
      isOpened: true,
    })
  }

  onOpened(e) {
    this.setState({
      id: e.currentTarget.dataset.id
    })
  }


  handleClose() {
    this.setState({
      isOpened: false
    })
  }

  handleCancel() {
    this.setState({
      isOpened: false
    })
  }

  handleConfirm = async (e) => {
    if (this.state.id) {
      await this.props.orderStore.deleteUserShippingAddress(this.state.id)
      Taro.showToast({ title: '已删除', icon: 'none' });
      let index = this.addressList.findIndex(m => m.id == this.state.id);
      this.addressList.splice(index, 1);
      this.setState({ isOpened: false });
    }
  }

  async chooseAddress() {
    Taro.chooseAddress({

    }).then(async (res) => {
      this.address = new UserShippingAddressInputDto();
      this.address.receiptUserName = res.userName;
      this.address.address = res.detailInfo;
      this.address.mobilephone = res.telNumber;
      this.address.isDefault = true;
      await this.props.orderStore.getAreaByName(res.countyName);
      const { area } = this.props.orderStore;
      if (area) {
        this.address.areaCode = area.value;
        await this.props.orderStore.createOrUpdateUserShippingAddress(this.address);
        this.address = this.props.orderStore.address
        Taro.showToast({ title: '导入地址成功', icon: 'none' });
        this.getAddressList()
        this.setOrderAddress(this.address)
      }
      else {
        Taro.showToast({ title: '导入地址失败', icon: 'none' });
      }

    })
  }

  selectAddrss(item) {
    if (this.$router.params.prev == "order") {
      this.setOrderAddress(item)
      this.backToOrder()
    }
    if (this.$router.params.prev == "index") {
      this.setOrderAddress(item)
      this.backToOrder()
    }
  }
  setOrderAddress(item) {
    var pages = getCurrentPages();
    if (this.$router.params.prev == "order") {
      var prevPage = pages.find(m => m.route == 'pages/profile/order/detail')
      if (prevPage) {
        prevPage.setData({
          defaultAddress: item,
        })
      }
      var prevPage = pages.find(m => m.route == 'pages/index/share')
      if (prevPage) {
        prevPage.setData({
          defaultAddress: item,
        })
      }
    }

    if (this.$router.params.prev == "index") {
      var prevPage = pages.find(m => m.route == 'pages/index/index')
      if (prevPage) {
        prevPage.setData({
          defaultAddress: item,
        })
      }
    }
  }

  backToOrder() {
    Taro.navigateBack({
      delta: 1
    })
  }

  render() {

    return (
      <View className='address-wrap'>
        <AtModal
          isOpened={this.state.isOpened}
          title='确认删除该地址吗？'
          cancelText='取消'
          confirmText='确认'
          onClose={this.handleClose}
          onCancel={this.handleCancel}
          onConfirm={this.handleConfirm}
        />
        <View className='address-list'>
          {
            this.addressList.map((item, index) => (
              <AtSwipeAction autoClose key={index} disabled={this.canDelete} options={this.swiperOptions} onClick={this.delete} onOpened={this.onOpened} data-id={item.id}>
                <View className='address-item ratina-bd bd-b' onClick={this.selectAddrss.bind(this, item)}>
                  <View className='addr-hd'>
                    <Text className='name'>{item.receiptUserName}</Text>
                    {item.isDefault && <Text className='default-tag'>默认</Text>}
                  </View>
                  <View className='addr-bd'>
                    <Text className='tel'>{item.mobilephone}</Text>
                    <Text className='addr-disc'>{item.areaCodeDisplayName}{item.address}</Text>
                  </View>
                  <View className='addr-ft' data-id={item.id} onClick={this.gotoAddressEdit.bind(this)}>
                    <AtIcon value='edit' size='18' color='#d33e2a' />
                  </View>
                </View>
              </AtSwipeAction>

            ))
          }
        </View>

        <View className='fixed-btns ratina-bd bd-t'>
          <AtForm reportSubmit={true} onSubmit={this.gotoAddressEdit.bind(this)}>
            <AtButton className='addr-btn' size='small' type='primary' formType="submit">新建地址</AtButton>
          </AtForm>
          <AtButton className='addr-btn' size='small' onClick={this.chooseAddress.bind(this)}>
            <AtIcon prefixClass='icon' value='weixin' size='14' color='#1daf3c' />
            导入微信地址
          </AtButton>
        </View>
      </View>
    )
  }
}

export default Index
